package com.tools.service.impl;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.tools.commons.response.ResponseCode;
import com.tools.commons.utils.IdGenerator;
import com.tools.commons.utils.JsonUtil;
import com.tools.config.UploadProperties;
import com.tools.service.UploadStrategy;
import lombok.AllArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import java.io.InputStream;

@Service
@ConditionalOnProperty(value = "upload.strategy.type", havingValue = "qiniu")
@AllArgsConstructor
public class QiNiuUploadStrategy implements UploadStrategy {
    UploadProperties properties;

    @Override
    public String upload(InputStream inputStream) {
        String key = IdGenerator.uuid();
        uploadToQiNiu(inputStream, key);
        return key;
    }

    private void uploadToQiNiu(InputStream inputStream, String key) {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region1());
//...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
//...生成上传凭证，然后准备上传
        String accessKey = properties.getAk();
        String secretKey = properties.getSk();
        String bucket = "pics";

        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(inputStream, key, upToken, null, "image/png");
            //解析上传成功的结果
            DefaultPutRet putRet = JsonUtil.string2Obj(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
                ResponseCode.BAD_REQUEST.throwException("服务器错误");
            }
        }
    }

    @Override
    public String getType() {
        return "qiniu";
    }
}
